# -*- coding: utf-8 -*-

#
# peerscape.http.controllers.content
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors:
#       Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from webob import Response
from webob.exc import HTTPBadRequest, HTTPMovedPermanently, HTTPOk

from peerscape.lib import json
from peerscape.http.color import get_safety_color
from peerscape.http.controllers import BaseController

class Content(BaseController):
    def index(self, req):
        # check the type before proceeding
        redir_url = self.exclude_type(req, ['principal','group','application'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('content.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['safety_color'] = get_safety_color(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['contentInfo'] = self.process_content_info(db, v['hexlabel'])
            
            # subscribe to the application dataset
            if v['contentInfo']['app'].get('iid'):
                db.subscribe(v['contentInfo']['app']['iid'])

            # try to make sure that index.html exists
            db.blocking_get(v['hexlabel'], '/application/index.html', timeout=20)

            # make it so
            return view.render(**v)
        else:
            return None


    def header(self, req):
        view = self.load_view('content.header.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['safety_color'] = get_safety_color(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            '''
            #[TODO: this won't work as hexlabel is unavailable (for setting the header colour)]
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']
            v['friend_list'] = self.process_friend_list(db, v['hexlabel'], v['my_iid'])
            v['is_friend'] = v['friend_list']['items'].has_key(db.get_my_iid())
            '''
            v['contentInfo'] = self.process_content_info(db, v['hexlabel'])

            # make it so
            return view.render(**v)
        else:
            return None


    def info(self, req):
        v = {}
        db = req.environ['peerscape.db']
        v['hexlabel'] = req.urlvars['peerscape.hexlabel']
        v['contentInfo'] = self.process_content_info(db, v['hexlabel'])

        # make it so
        res = HTTPOk()
        res.content_type = 'application/json';
        if req.GET.has_key('jsonp'):
            res.body = '%s(%s)' % (req.GET['jsonp'], json.dumps(v['contentInfo']))
        else:
            res.body = json.dumps(v['contentInfo'])
        return res

    def info_js(self, req):
        # check the type before proceeding
        redir_url = self.exclude_type(req, ['principal','group','application'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('content.info.js')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['safety_color'] = get_safety_color(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['contentInfo'] = self.process_content_info(db, v['hexlabel'])

            # make it so
            return view.render(**v)
        else:
            return None

    def picture_path(self, req):
        if req.method == 'GET':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            ret = db.get_profile_picture(v['hexlabel'])
            if not ret:
                ret = '/static/dummy_application.png'

            # return root-relative path to picture
            return ret

    def picture(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            if req.POST.has_key('value'):
                new_value = req.POST['value']
                db.set_profile_picture(v['hexlabel'], new_value)
                
                # echos back path of new picture
                return db.get_profile_picture(v['hexlabel'])

            elif req.POST.has_key('ref'):
                value_ref = req.POST['ref']
                if value_ref.startswith('/get'):
                    value_ref = value_ref[4:]

                new_value = db.get(v['hexlabel'], value_ref)
                if not new_value:
                    return HTTPBadRequest()

                db.set_profile_picture(v['hexlabel'], new_value)
                
                # echos back path of new picture
                return db.get_profile_picture(v['hexlabel'])
            else:
                return HTTPBadRequest()
        else:
            # GET
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            ret = db.get_profile_picture(v['hexlabel'])
            if not ret:
                ret = '/static/dummy_application.png'

            # redirect to get rather than re-implement
            ret = '/get%s' % ret
            return HTTPMovedPermanently(location=ret)

    def title(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            if req.POST.has_key('value'):
                new_value = req.POST['value']
                db.set_profile_name(v['hexlabel'], new_value)
                
                # echos back new value
                return db.get_profile_name(v['hexlabel'])
            else:
                return HTTPBadRequest()
        else:
            # GET
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            ret = db.get_profile_name(v['hexlabel'])
            return ret


    def text(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            if req.POST.has_key('value'):
                new_value = req.POST['value']
                old_value, visibility = db.get_profile_text(v['hexlabel'])
                db.set_profile_text(v['hexlabel'], new_value, public=visibility)
                
                # echos back new value
                new_value, visibility = db.get_profile_text(v['hexlabel'])
                return new_value
            else:
                return HTTPBadRequest()
        else:
            # GET
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']

            ret, visibility = db.get_profile_text(v['hexlabel'])
            if not ret:
                ret = ''

            return ret
        
